<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    //
    public function index(Request $request)
    {
        $pageIndex = $request->get('pageIndex');
        $pageSize = $request->get('pageSize');

        $list = Category::query()->orderByDesc('sort')->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);

        return $this->response($list);
    }

    public function store(Request $request)
    {
        $data = $request->all();

        $category = Category::query()->create($data);

        return $this->response($category,'添加成功');
    }

    public function show($id)
    {
        return $this->response(Category::query()->find($id));
    }

    public function update($id,Request $request)
    {
        $data = $request->all();

        $category = Category::query()->where('id', $id)->first();

        if (!$category) return $this->response([],'分类未找到',500);

        unset($data['updated_at']);

        $res = $category->update($data);

        return $res ? $this->response($res,'修改成功') : $this->response($res,'修改失败');
    }

    public function delete($id)
    {
        $banner = Category::query()->where('id', $id)->first();

        if (!$banner) return $this->response([],'分类未找到',500);

        $res = $banner->delete();

        return $res ? $this->response($res,'删除成功') : $this->response($res,'删除失败');
    }
}
